<template>
    <div class="side-container">
        <div class="mx-3 mt-4">
            <el-button
                v-if="route.path.startsWith('/apply/docs/chatting')"
                type="primary"
                size="large"
                class="w-full mb-4"
                @click="handleUpload"
            >上传文档</el-button>
        </div>
        <div class="mx-3">
            <el-input :prefix-icon="Search" placeholder="搜索文档" />
        </div>
        <div
            v-loading="firstLoading"
            class="mt-3 py-2 h-full overflow-hidden border-t border-br-lighter"
        >
            <el-scrollbar>
                <div
                    v-for="(item, index) in dataList"
                    :key="index"
                    class="sidebar-item"
                    :class="{ 'active': item.code === currCode }"
                    @click="handleSwitch(item.code)"
                >
                    <el-image
                        class="shrink-0 w-[30px] h-[30px]"
                        loading="lazy"
                        :lazy="true"
                        :src="suffixUtil.findUnitIcon(item.name)"
                    />
                    <div class="w-full ml-2">
                        <h3 class="mb-2 text-base text-tx-primary line-clamp-2">{{ item.name }}</h3>
                        <div class="meta flex justify-between items-center text-xs">
                            <span>{{ item.create_time }}</span>
                            <div class="grid gap-2.5 grid-cols-2">
                                <icon
                                    name="el-icon-EditPen"
                                    class="icon-edit"
                                    @click.stop="handleUpdate(item)"
                                />
                                <icon
                                    name="el-icon-Delete"
                                    class="icon-delete"
                                    @click.stop="handleDelete(item.code)"
                                />
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="dataList.length <= 0 && !firstLoading" class="text-center">
                    <el-empty description="暂无文档" />
                </div>
            </el-scrollbar>
        </div>

        <ClientOnly>
            <popup
                :show="editState.show"
                width="480px"
                title="重命名"
                :async-close="true"
                :loading="editState.loading"
                @close="editState.show = false"
                @confirm="handleUpdate"
            >
                <el-form class="p-6 pb-0">
                    <el-form-item prop="name">
                        <el-input
                            v-model="editState.name"
                            placeholder="请输入文档名称"
                            maxlength="200"
                        />
                    </el-form-item>
                </el-form>
            </popup>
        </ClientOnly>
    </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { watchDebounced } from '@vueuse/core'
import suffixUtil from '~/utils/suffix'
import docsFilesApi from '~/api/apply/docs/files'

const route = useRoute()
const router = useRouter()

// 首次加载
const firstLoading = ref<boolean>(true)

// 编辑状态
const editState = ref({
    loading: false,
    show: false,
    code: '',
    name: ''
})

// 文件参数
const keywords = ref<string>('')
const currCode = ref<string>(String(route.query.code))
const dataList = ref<DocFilesListResponse[]>([])

// 查询列表
const queryLists = async () => {
    dataList.value = await docsFilesApi.lists({
        keyword: keywords.value
    })
}

/**
 * 文件编辑
 */
const handleUpdate = async (row?: any) => {
    if (row) {
        editState.value.show = true
        editState.value.code = row.code
        editState.value.name = row.name
    } else {
        editState.value.show = true
        await docsFilesApi.rename({
            code: editState.value.code,
            name: editState.value.name
        }).finally(() => {
            editState.value.loading = false
        })

        await queryLists()
        editState.value.show = false
        editState.value.name = ''
        feedback.msgSuccess('重命名成功')
    }
}

/**
 * 文件删除
 *
 * @param {string} code
 * @author zero
 */
const handleDelete = async (code: string) => {
    feedback.confirm('您确定要删除该文件吗?')
        .then(async () => {
            await docsFilesApi.delete({ code })
            await queryLists()
            if (
                code === currCode.value &&
                route.path.startsWith('/apply/docs/chatting')
            ) {
                if (dataList.value.length) {
                    handleSwitch(dataList.value[0].code)
                }
            }
        }).catch(() => {})
}

/**
 * 文件切换
 *
 * @param {string} code
 * @author zero
 */
const handleSwitch = (code: string) => {
    keywords.value = ''
    currCode.value = code
    router.replace({
        path: '/apply/docs/chatting',
        query: { code }
    })
}

/**
 * 上传切换
 */
const handleUpload = () => {
    currCode.value = ''
    router.push({
        path: '/apply/docs/uploader'
    })
}

/**
 * 监听路径变动
 */
watchDebounced(
    () => route.query.code,
    async (val) => {
        currCode.value = String(val)
    }, {
        immediate: true
    }
)

/**
 * 首次进入加载
 */
onMounted(async () => {
    firstLoading.value = true
    await queryLists().finally(() => {
        firstLoading.value = false
    })
})

defineExpose({
    resetSidebar: async () => {
        await queryLists()
    }
})
</script>

<style scoped lang="scss">
.side-container {
    display: flex;
    flex: 0 0 320px;
    flex-direction: column;
    height: 100%;
    margin-right: 10px;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    .sidebar-item {
        display: flex;
        align-items: center;
        padding: 10px 10px 10px 8px;
        margin: 5px 10px;
        color: var(--el-text-color-secondary);
        cursor: pointer;
        border-radius: .5rem;
        &.active {
            color: var(--el-color-primary);
            background-color: var(--el-color-primary-light-9);
            h3 {
                color: var(--el-color-primary);
            }
        }
        &:not(.active):hover {
            background-color: var(--el-bg-color-page);
        }
        .icon-edit:hover {
            color: var(--el-color-primary);
        }
        .icon-delete:hover {
            color: var(--el-color-error);
        }
    }
}
</style>
